function C = coxC(covariates,survivalTime,censorvec)


%%%%%
% This function computes the C statistic (AUC) for Cox regression models. 
%
% The method is described in:
% R. B. D'Agostino and B. Nam. Evaluation of the performance of survival analysis models: descrimination and calibration measures. Handbook of Statistics, 23:1-25, 2003. 
%
% Inputs:
% covariates: 2D matrix containing covariates; rows are individuals and columns are covariates
% survivalTime - 1D vector containing survival times in days.
% censorvec - 1D boolean vector indicating right-censored data; 0 = not censored, 1 = right-censored. Should correspond to the elements in survivalTime.
%
% Written by Joon Lee, May. 17, 2011
%%%%%


[b,logl,H]=coxphfit(covariates,survivalTime,'censoring',censorvec,'baseline',0);
risk=exp(covariates*b);
prob=1-exp(-H(end,2)).^risk;
n=length(survivalTime);
C=0;
Q=0;

for i=1:n-1
    for j=i+1:n
        
        if ~censorvec(i) && ~censorvec(j) 
            Q=Q+1;
            if (survivalTime(i)<survivalTime(j) && prob(i)>prob(j)) || (survivalTime(i)>survivalTime(j) && prob(i)<prob(j)) 
                C=C+1;
            end                       
        elseif ~censorvec(i) && censorvec(j) && survivalTime(i)<survivalTime(j)
            Q=Q+1;
            if prob(i)>prob(j)
                C=C+1;
            end
        elseif censorvec(i) && ~censorvec(j) && survivalTime(i)>survivalTime(j)
            Q=Q+1;
            if prob(i)<prob(j)
                C=C+1;
            end
        end
        
    end    
end

C=C/Q;
